package com.android.common.mvp.view.fragment;

import android.graphics.drawable.Drawable;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.android.common.R;
import com.android.common.base.BaseFragment;
import com.android.common.mvp.model.MediaItem;
import com.android.common.utils.GlideUtils;
import com.android.common.utils.LogUtil;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.luck.picture.lib.photoview.PhotoView;

public class PicturePreviewFragment extends BaseFragment {

    private final static String TAG = "PicturePreview";

    private MediaItem mMediaItem;

    private PhotoView mPhImagePreview;

    @Override
    protected int onSetRootViewId() {
        return R.layout.fragment_picture_preview;
    }

    @Override
    protected void onFindView() {
        super.onFindView();
        mPhImagePreview = mRootView.findViewById(R.id.pv_image_preview);
    }

    @Override
    protected void onInitView() {
        super.onInitView();
        String path = mMediaItem.path;
        LogUtil.d(TAG, "picture url = " + path);
        GlideUtils.with().loadTokenImage(path, mPhImagePreview, new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                Toast.makeText(mActivity, getString(R.string.pic_load_failed), Toast.LENGTH_SHORT).show();
                getActivity().finish();
                return true;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        });
    }

    @Override
    protected void onInitEvent() {
        super.onInitEvent();
        mPhImagePreview.setOnViewTapListener((view, x, y) -> {
            getActivity().finish();
        });

        mPhImagePreview.setOnPhotoTapListener((view, x, y) -> {
            getActivity().finish();
        });
    }

    @Override
    protected boolean onNeedToolBar() {
        return false;
    }

    public void setMediaItem(MediaItem mediaItem){
        mMediaItem = mediaItem;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
